#!/bin/python3

import carla
import pygame

import argparse
import random
import time

class CarlaEnv(object):
    def __init__(self, host='localhost', port=2000, seed=None, *args, **kwargs):
        self.host = host
        self.port = port
        self.client = None
        self.world = None
        self.map_name = None
        self.weather = None
        self.available_maps = None
        self.seed = None
    
    def reset(self):
        self._connect()
        self._set_random_map()
        self._set_random_weather()

    def _connect(self):
        self.client = carla.Client(self.host, self.port)
        self.client.set_timeout(10.0)
        print("Connected to Carla server success")
    
    def _set_random_map(self):
        self.available_maps = self.client.get_available_maps()
        if not self.seed:
            self.seed = time.time()
        random.seed(self.seed)
        self.map_name = random.choice(self.available_maps)
        self.world = self.client.load_world(self.map_name)
        print("Loaded map: {}".format(self.map_name))
    
    def _run_step(self):
        self.world.tick()
    
    def _set_random_weather(self):
        from .nature import Nature

        nature = Nature(self.seed)
        self.weather = nature.generate()
        self.world.set_weather(self.weather)
    
    def set_sync_mode(self, sync_mode=True):
        settings = self.world.get_settings()
        settings.synchronous_mode = sync_mode
        self.world.apply_settings(settings)
        

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Carla Environment')
    parser.add_argument('--host', type=str, default='localhost')
    parser.add_argument('--port', type=int, default=2000)
    args = parser.parse_args()
    print(args)
    env = CarlaEnv(args.host, args.port)
    env._connect()
    env._set_random_map()
    env._set_random_weather()
    
